package com.uchengwang.ui.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.UserConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.functions.jpush.JpushSetAlisTagUtil;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.login.ui.LoginActivity;
import com.uchengwang.ui.cm_ui.me.bean.LinkAccountBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RongChatManager;
import com.uchengwang.ui.cm_ui.umsg.bean.SchoolClubBean;
import com.uchengwang.ui.cm_ui.umsg.ui.ClubMainActivity;
import com.umeng.analytics.MobclickAgent;

import io.rong.imkit.RongIM;


/**
 * Created by U城网 on 2017/8/8.
 */

public class SwitchAccountUtils {
    private static SwitchAccountUtils utils;

    private SwitchAccountUtils (){}

    public static SwitchAccountUtils getUtils() {
        if (utils == null){
            utils = new SwitchAccountUtils();
        }
        return utils;
    }

    /**
     * 社团账号切换到个人账号
     * */
    public void toPersonAccount(final Context context){
            //切换账号 切换到个人账号
            LoadingUtils.getUtils().loading(context);
            MapRequest map = new MapRequest();
            HttpManager.newInstance((Activity) context).query(UserConfig.SwitchAccount.method, UserConfig.SwitchAccount.URL_PER, map, new HttpCallBack() {
                @Override
                public void onError(int status, String msg) {
                    LoadingUtils.getUtils().hide();
                    UCommonUtil.getUtil().showToast(context, "切换失败");
                }

                @Override
                public void onResp(int status, String msg, String data) {
                    LoadingUtils.getUtils().hide();
                    if (status != 0){
                        UCommonUtil.getUtil().showToast(context, msg);
                        if (!TextUtils.isEmpty(msg) && msg.equals("身份校验错误")){
                            //重新登陆
                            context.startActivity(new Intent(context, LoginActivity.class));
                            return;
                        }
                    }else {
                        if (msg.equals("身份校验错误")){
                            //重新登陆
                            context.startActivity(new Intent(context, LoginActivity.class));
                            return;
                        }
                        UserBean userBean = JsonUtils.getManager().stringToBean(data, UserBean.class);
                        if (userBean == null){
                            return;
                        }
                        RongChatManager.getUtils().changeRy(context);
                        //将融云token置空
                        SPUtils.getPreferences(context).setRyToken("");

                        UChengApplication.userRole = 1;
                        UChengApplication.uid = userBean.getId();
                        UChengApplication.TOKEN = userBean.getToken();
                        UChengApplication.nickName = userBean.getNickName();
                        UChengApplication.userAvatar = userBean.getUserAvatar();
                        UChengApplication.uniId = userBean.getUniId();
                        UChengApplication.myUniId = userBean.getUniId();
                        UChengApplication.mySchoolName = userBean.getUniName();
                        UChengApplication.schoolName = userBean.getUniName();
                        UChengApplication.uniDataId = userBean.getUniDataId();
                        UChengApplication.sex = userBean.getSex();

                        SPUtils.getPreferences(context).putInt(BaseConfig.SEX, userBean.getSex());
                        SPUtils.getPreferences(context).putInt(BaseConfig.USER_ROLE, 1);
                        SPUtils.getPreferences(context).setAccountId(userBean.getId());
                        SPUtils.getPreferences(context).setRealName(userBean.getRealName());
                        SPUtils.getPreferences(context).putString(BaseConfig.NICK_NAME, userBean.getNickName());
                        SPUtils.getPreferences(context).putString(BaseConfig.USER_AVATAR, userBean.getUserAvatar());
                        SPUtils.getPreferences(context).putLong(BaseConfig.UNI_ID, userBean.getUniId());
                        SPUtils.getPreferences(context).putString(BaseConfig.UNI_NAME, userBean.getUniName());
                        SPUtils.getPreferences(context).setToken(userBean.getToken());
                        SPUtils.getPreferences(context).setTokenTime();
                        SPUtils.getPreferences(context).putLong(BaseConfig.UNI_DATA_ID, userBean.getUniDataId());
                        SPUtils.getPreferences(context).setLinkMainToken(userBean.getToken());
                        SPUtils.getPreferences(context).putString(BaseConfig.USER_SIGN, userBean.getUserSign());

                        LiteOrmDBUtil.getLiteOrm(context);
                        //跳到MainActivity[社团切换到个人]
                        ActivityUtils.getUtils().clearClubMainActivity();
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra(BaseConfig.INDEX, 0);
                        context.startActivity(intent);


                    }
                }
            });
    }

    /**
     * 个人切换到社团账号
     * */
    public void toClubAccount(final Context context, final SchoolClubBean bean){
        LoadingUtils.getUtils().loading(context);
        //切换账号
        MapRequest map = new MapRequest();
        map.put(BaseConfig.ID, bean.getUid());

        HttpManager.newInstance((Activity) context).query(UserConfig.SwitchAccount.method, UserConfig.SwitchAccount.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                UCommonUtil.getUtil().showToast(context, "切换失败");
                LoadingUtils.getUtils().hide();
            }

            @Override
            public void onResp(int status, String msg, String data) {
                LoadingUtils.getUtils().hide();
                if (status != 0){
                    UCommonUtil.getUtil().showToast(context, msg);
                }else {
                    if (TextUtils.isEmpty(data)){
                        return;
                    }
                    RongChatManager.getUtils().changeRy(context);
                    //将融云token置空
                    SPUtils.getPreferences(context).setRyToken("");

                    JSONObject object = JsonUtils.getManager().getJSONObject(data);
                    String token = object.getString("token");
//                                UCommonUtil.getUtil().showToast(context, "切换成功");
                    UChengApplication.clubId = bean.getUid();
                    UChengApplication.nickName = bean.getOrgName();
                    UChengApplication.userAvatar = bean.getLogoImg();
                    UChengApplication.userRole = 2;
                    UChengApplication.TOKEN = token;
                    UChengApplication.uniId = bean.getUniId();
                    UChengApplication.myUniId = bean.getUniId();

//                    UChengApplication.schoolName = bean.getUniName();
//                    UChengApplication.mySchoolName = bean.getUniName();

                    SPUtils.getPreferences(context).putInt(BaseConfig.USER_ROLE, 2);
                    SPUtils.getPreferences(context).setAccountId(bean.getUid());
                    SPUtils.getPreferences(context).putString(BaseConfig.NICK_NAME, bean.getOrgName());
                    SPUtils.getPreferences(context).putString(BaseConfig.USER_AVATAR, bean.getLogoImg());
                    SPUtils.getPreferences(context).putLong(BaseConfig.UNI_ID, bean.getUniId());
                    SPUtils.getPreferences(context).putString(BaseConfig.UNI_NAME, bean.getUniName());
                    SPUtils.getPreferences(context).setToken(token);
                    SPUtils.getPreferences(context).setTokenTime();
                    SPUtils.getPreferences(context).putString(BaseConfig.USER_SIGN, bean.getOrgSign());

                    LiteOrmDBUtil.getLiteOrm(context);
                    //跳到ClubMainActivity【个人切换到社团】
                    ActivityUtils.getUtils().clearMainActivity();
                    Intent intent1 = new Intent(context, ClubMainActivity.class);
                    context.startActivity(intent1);
                    ((Activity) context).finish();



                }
            }
        });
    }


    /**
     * 个人获取社团token
     * */
    public void getClubToken(final Context context, final long clubUid, final OnResultListener listener){
        //切换账号
        MapRequest map = new MapRequest();
        map.put(BaseConfig.ID, clubUid);

        HttpManager.newInstance((Activity) context).query(UserConfig.SwitchAccount.method, UserConfig.SwitchAccount.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                UCommonUtil.getUtil().showToast(context, "切换失败");

                listener.onResult(status, msg, 0, null);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                if (status != 0){
                    UCommonUtil.getUtil().showToast(context, msg);
                    listener.onResult(status, msg, 0, null);
                }else {
                    if (TextUtils.isEmpty(data)){
                        listener.onResult(status, msg, 0, null);
                        return;
                    }

                    JSONObject object = JsonUtils.getManager().getJSONObject(data);
                    String token = object.getString("token");

                    listener.onResult(status, msg, 0, token);
                }
            }
        });
    }

    /**
     * 关联账号的切换
     * */
    public void switchLink(Context context, LinkAccountBean bean){
        ActivityUtils.getUtils().clearMainActivity();

        RongChatManager.getUtils().changeRy(context);
        //将融云token置空
        SPUtils.getPreferences(context).setRyToken("");

        UChengApplication.userRole = bean.getFakerUserRole();
        UChengApplication.uid = bean.getFakerUid();
        UChengApplication.sex = bean.getSex();

        String token = bean.getFakerToken();
        if (!TextUtils.isEmpty(token)){
            UChengApplication.TOKEN = token;
        }else {
            //切换到主账号 主账号后台因为安全为题没有返回主账号的token
            UChengApplication.TOKEN = SPUtils.getPreferences(context).getLinkMainToken();
        }
        UChengApplication.nickName = bean.getFakerNickName();
        UChengApplication.userAvatar = bean.getFakerUserAvatar();
        UChengApplication.myUniId = bean.getFakerUniId();
        UChengApplication.mySchoolName = bean.getFakerUniName();

        SPUtils.getPreferences(context).putInt(BaseConfig.SEX, bean.getSex());
        SPUtils.getPreferences(context).putInt(BaseConfig.USER_ROLE, bean.getFakerUserRole());
        SPUtils.getPreferences(context).setAccountId(bean.getFakerUid());
        SPUtils.getPreferences(context).putString(BaseConfig.NICK_NAME, bean.getFakerNickName());
        SPUtils.getPreferences(context).putString(BaseConfig.USER_AVATAR, bean.getFakerUserAvatar());
        SPUtils.getPreferences(context).putLong(BaseConfig.UNI_ID, bean.getFakerUniId());
        SPUtils.getPreferences(context).putString(BaseConfig.UNI_NAME, bean.getFakerUniName());
        SPUtils.getPreferences(context).setToken(UChengApplication.TOKEN);
        SPUtils.getPreferences(context).setTokenTime();

        SPUtils.getPreferences(context).putBoolean(BaseConfig.IS_AUTHEN, true);

        LiteOrmDBUtil.getLiteOrm(context);
        //关联账号切换
        UCommonUtil.getUtil().showToast(context, "登录成功");
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);

    }

    /**
     * 转让社团后账号退出
     * */
    public void transferClubexit(Context context){
        RongIM.getInstance().logout();//退出

        MobclickAgent.onKillProcess(context);//友盟统计

        JpushSetAlisTagUtil.getUtil().setNullAlis(context);

        SPUtils.getPreferences(context).setRyToken("");//融云token置空

        LiteOrmDBUtil.getLiteOrm(context).exit();

        UChengApplication.TOKEN = "";
        UChengApplication.uid = 0;
        UChengApplication.nickName = "";
        UChengApplication.uniId = 0;
        UChengApplication.myUniId = 0;
        UChengApplication.schoolName = "";
        UChengApplication.mySchoolName = "";
        UChengApplication.userAvatar = "";
        UChengApplication.userRole = 0;
        UChengApplication.isAuthen = false;

        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);

    }

}
